using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ImageReview
{
    public partial class Submit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session[ "ShowBarcodeFlag" ] = true;
            Session[ "ShowDeleteLink" ] = true;
            Session[ "ConsignmentNumberReadonly" ] = false;
            Session[ "GoodsIDReadonly" ] = false;
            Session[ "CurrentPage" ] = CurrentPage.Submit;

            if (Request.QueryString["ready"] != null)
            {
                string ready = Request.QueryString["ready"];
                if (ready.Equals("1"))
                {
                    this.nextPanel.Visible = true;
                }
                else
                {
                    this.nextPanel.Visible = false;
                }
            }
            else
            {
                this.nextPanel.Visible = false;
            }

            // Determine the user name, less domain
            string username = User.Identity.Name;
            username = username.Substring( username.LastIndexOf( '\\' ) + 1 );

            // Maybe determine the default folder for this user.
            if( Session["FolderToLoad"] == null || String.IsNullOrEmpty( Session["FolderToLoad"].ToString( ) ) )
            {
                // Retrieve configuration xml file.
                TPDSConfig.TPDSConfig ConfigFile = TPDSWEBConfig.Load( Server.MapPath( @"~/" ) );
                if( ConfigFile == null )
                {
                    Response.Write( "<script type=\"text/javascript\">alert('Unable to load the configuration file (config.xml).');</script>" );
                    return;
                }

                // Determine the folder for this user.
                Session["FolderToLoad"] = Server.MapPath( "~/" + Path.Combine( ConfigFile.ImageMonitorRootFolder, username ) );
                Session["ImageFolder"] = ConfigFile.ImageMonitorRootFolder + "\\" + username;
            }

            // Cannot go further without a folder in session state
            if( Session[ "FolderToLoad" ] == null || String.IsNullOrEmpty( Session[ "FolderToLoad" ].ToString( ) ) )
                return;

            if (!IsPostBack)
            {
                this.lblUsername.Text = "User: ";
                this.lblUsername2.Text = username;

                FolderName.Text = Session[ "FolderToLoad" ].ToString( );
                //this.FileUploader1.Adapters.Add(new com.flajaxian.FileSaverAdapter() { FolderName = Session["ImageFolder"].ToString() });
            }
            // Upload Images
            if (Request.Files.Count > 0)
            {
                HttpFileCollection Files = Request.Files;
                string savePath = Session["FolderToLoad"].ToString() + "\\"; 

                for (int i = 0; i < Files.Count; i++)
                {
                    HttpPostedFile postedFile = Files.Get(i);
                    string tempName = postedFile.FileName.ToString();
                    string fileName = tempName.Substring(tempName.LastIndexOf('\\') + 1);

                    postedFile.SaveAs(savePath + fileName);
                }

            }
            // List content now.
            ListFiles();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Retrieve configuration xml file.
            TPDSConfig.TPDSConfig ConfigFile = TPDSWEBConfig.Load( Server.MapPath( @"~/" ) );
            if( ConfigFile == null )
            {
                Response.Write( "<script type=\"text/javascript\">alert('Unable to load the configuration file (config.xml).');</script>" );
                return;
            }

            List<TPDSControl.Image> images = new List<TPDSControl.Image>( );

            DirectoryInfo directoryInfo = new DirectoryInfo( Session[ "FolderToLoad" ].ToString( ) );

            if( directoryInfo.Exists )
            {
                //create a list of all existing images in imagesets
                ArrayList existingImages = new ArrayList( );
                List<TPDSControl.ImageSet> existingImagesets = TPDSControl.ImageSet.LoadAll( directoryInfo.FullName );
                foreach( TPDSControl.ImageSet imgset in existingImagesets )
                {
                    foreach( TPDSControl.Image img in imgset.Images )
                    {
                        existingImages.Add( Path.GetFileName( img.Filename ).ToUpper( ) );
                    }
                }

                List<FileInfo> fileInfoList = new List<FileInfo>( );
                TPDSControl.Image image = null;

                foreach( FileInfo fi in directoryInfo.GetFiles( ConfigFile.BarcodeImageFileMask ) )
                {
                    if( ( !fi.Name.ToUpper( ).Contains( "_THUMB" ) ) && ( !existingImages.Contains( fi.Name.ToUpper( ) ) ) )
                    {
                        fileInfoList.Add( fi );
                    }
                }

                fileInfoList.Sort( new TPDSConfig.Utils.FileInfoComparer( ) ); //sort files by date and name

                foreach( FileInfo fi in fileInfoList )
                {
                    image = new TPDSControl.Image( );
                    string filename = Path.GetFileName( fi.FullName );
                    string thumbnailFilename = Path.GetFileNameWithoutExtension( fi.FullName ) + "_thumb" + Path.GetExtension( fi.FullName );
                    string path = Path.Combine( ( new DirectoryInfo( fi.DirectoryName ) ).Parent.ToString( ), ( new DirectoryInfo( fi.DirectoryName ) ).Name );
                    image.Filename = Path.Combine( path, filename );
                    image.ThumbnailFilename = Path.Combine( path, thumbnailFilename );
                    images.Add( image );
                }

                if( images.Count > 0 ) //only write a new imageset file if it will contain data
                {
                    TPDSControl.ImageSet imageset = new TPDSControl.ImageSet( );
                    imageset.Images = images;
                    imageset.Filepath = Path.Combine( directoryInfo.FullName, ( Guid.NewGuid( ).ToString( ) + ".set" ) );
                    imageset.Save( );
                }
            }
            string currentUrl = Request.Url.ToString();
            string currentUri = currentUrl.Substring(0, currentUrl.LastIndexOf("aspx")) + "aspx";
            Response.Redirect(currentUri + "?ready=1" , false);
        }


        private void ListFiles()
        {
            if( !Directory.Exists( Session[ "FolderToLoad" ].ToString( ) ) )
            {
                Response.Write( "<script type=\"text/javascript\">alert('Users image folder does not exist.');</script>" );
                return;
            }

            // Retrieve configuration xml file.
            TPDSConfig.TPDSConfig ConfigFile = TPDSWEBConfig.Load( Server.MapPath( @"~/" ) );
            if( ConfigFile == null )
            {
                Response.Write( "<script type=\"text/javascript\">alert('Unable to load the configuration file (config.xml).');</script>" );
                return;
            }

            ImageList imagelist = (ImageList)this.LoadControl( "ImageList.ascx" );
            imagelist.FolderToLoad = Session[ "FolderToLoad" ].ToString();
            imagelist.ImageFilemask = ConfigFile.BarcodeImageFileMask;
            phImages.Controls.Add( imagelist );
        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            string nextPage = ResolveClientUrl("~/Default.aspx");
            Response.Redirect(nextPage, false);
        }
    }
}
